#coding=utf-8

import time
import random
from Cookie import SimpleCookie
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class Log(db.Model):
  url = db.StringProperty(required=True)
  user = db.StringProperty(required=True)
  image = db.StringProperty()
  title = db.StringProperty() 
  clickTime = db.DateTimeProperty(auto_now_add=True)

class BrowseHistory(webapp.RequestHandler):
  def get(self):
	  # cookie
	  if self.request.cookies:
		browserId = self.request.cookies["bId"];
	  	# db
		termList = db.GqlQuery("SELECT * FROM Log WHERE user = :1", browserId)
		for term in termList:
			self.response.out.write( str(term.clickTime) + " ")
			self.response.out.write( term.title + " ")
			self.response.out.write( term.url + " ")
			self.response.out.write( "<img src="+ term.image +" height=100 width=100><br>")
			

	  else:
		self.response.out.write("no query record for this user")

class Patch(webapp.RequestHandler):
  def get(self):
	  
		# get
	  	self.request.charset='utf-8'
	  	url = self.request.get('url')
	  	title = self.request.get('t')
	  	selected = self.request.get('s')
		img_str = self.request.get('i')

		# process input
		for x in img_str.split('*'):
			imgSrc = x
			break

		# cookie
		c = SimpleCookie()
		c.load(self.request.cookies)
		# bid
		if not c.has_key("bId"):
			browserId = random.randint(1,10000000)
			c["bId"] = str(browserId)
			c["bId"]["expires"]= str(time.time() + 60*60*24*365)
			c["bId"]["path"]="/"
			header_value = c["bId"].output(header='').lstrip()
			self.response.headers._headers.append(('Set-Cookie', header_value))
		else:
			browserId = self.request.cookies["bId"]

		# db access
		term = Log(	url = url, 
				user = str(browserId),
				title = title,
				image = imgSrc)
		term.put()

		self.response.out.write("""<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<style>html{height:100%}body{margin:0;font:62.5% arial,sans-serif;height:100%;overflow:hidden}a,a:visited{color:#00c}div{font-size:130%}#details{float:left;margin-top:10px}#details p{padding:0;margin:0 0 2px}img{border:none}#outer-separator{clear:both;width:100%;border-bottom:2px solid #404040;border-top:1px solid #a0a0a0;margin:10px 0 0;padding:0;font-size:1px;overflow:hidden}#separator{background:#eaeaea;height:3px}table{font-size:100%}</style>
</head>
<body>
<table cellpadding=0 cellspacing=0 height="100%" width="100%">
<tr height="1%"><td style="top:0;width:100%">
	<div class=std style="background:#ebeff9;padding:6px 8px"><a href=""><img src= style="padding:0;margin:0;vertical-align:middle;border:0" title="" alt="" width=72 height=24></a><form style="display:inline" method=GET action=""><input type=hidden name=sa value="3">&nbsp;<input type=text name=q size=41 maxlength=2048 value="" title="">&nbsp;<input type=submit name="btnG" value=""></form>&nbsp;<a id=b2r href=""></a></div>
	<table cellpadding=0 cellspacing=0 width="100%"><tr><td><div id=details><p style="margin-bottom:4px">url: """+url+"""<br>title: """+title+"""<br>selected: """+selected+"""<br>img: <img src="""+imgSrc+""" height=100 width=100 alt=></p></div><td align=right valign=bottom><div style="padding-right:8px"><a href="""+url+""" style="text-decoration:none"><u></u>&nbsp;<img src= style="margin-bottom:-2px" height=15 width=15 alt=""></a></div></table>
	<div id=outer-separator><div id=separator></div></div>
<tr><td><iframe scrolling=auto id=rf src="""+url+""" frameborder=0 allowtransparency=true style="width:100%;height:100%"></iframe>
</table>
</body><script>var a = document.getElementById('rf');a && a.contentWindow && a.contentWindow.focus();</script></html>""")

		##<table cellpadding=0 cellspacing=0 width="100%"><tr><td><a href="" id=thumbnail><img src="" width=59 height=80 style="float:left;margin:10px 10px 0;border:1px solid" alt=""></a><div id=details><p style="margin-bottom:4px"><a href="" style="font-size:115%;font-weight:bold"></a></p></div><td align=right valign=bottom><div style="padding-right:8px"><a href="http://blog.cfan.com.cn/html/46/224646_itemid_11807.html" style="text-decoration:none"><u></u>&nbsp;<img src=/images/isr_c.gif style="margin-bottom:-2px" height=15 width=15 alt=""></a></div></table>

class MainHandler(webapp.RequestHandler):
  def get(self):
		self.response.out.write("""<html><head><title></title></head><body><a href="javascript:(function(){s='';if(window.getSelection)s=window.getSelection();else%20if%20(document.getSelection)s=document.getSelection();else%20if(document.selection)s=document.selection.createRange().text;img='';for (i=0;i<document.images.length;i++){if (document.images[i].height>200)img+=document.images[i].src+'*';}javascript:void(location.href='http://localhost:8080/patch?url='+encodeURIComponent(location.href)+'&t='+encodeURIComponent(document.title)+'&s='+encodeURIComponent(s)+'&i='+encodeURIComponent(img));})()">meow</a></body></html>""")


def main():
  application = webapp.WSGIApplication([('/', MainHandler),
	  ('/hist', BrowseHistory),
	  ('/patch', Patch)],
	  debug=True)
  run_wsgi_app(application)


if __name__ == '__main__':
  main()
